#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
#define endl '\n'
const int maxn = 100 + 50;
const int maxm = maxn * maxn;
const int INF = 1e8;

int dis[maxn][maxn];
int book[maxn];//book=0表示尚未扩展到的点
int n, m;
int lowcost[maxn];

/**
 * Prim算法 啊哈算法实现v1，O(n^2)
 * lowcost记录了已经扩展的集合（起点f)到未扩展集合(终点t)里最短路径ek（关键边，但是book数组没有保存这个边的起点,第二个版本会改进book数组，
 * @param v
 * @return
 */
int Prim(int v = 1) {
    memset(book, 0, sizeof(book));

    book[v] = 1;//先把{source} 加入已扩展集合
    for (int i = 1; i <= n; i++) {
        lowcost[i] = INF;
    }
    for (int i = 1; i <= n; i++) {
        lowcost[i] = dis[v][i];
    }

    int tot = 0;
    book[v] = 1;
    int cnt = 0;
    ++cnt;
    while (cnt < n) {
        int mincost = INF;//最短边的长度
        int j = -1;//最短边的终点
        for (int i = 1; i <= n; i++) {
            if (book[i] == 0 && lowcost[i] < mincost) {
                mincost = lowcost[i];
                j = i;
            }
        }
        if (j == -1) {
            break;
        }
        for (int i = 1; i <= n; i++) {
            if (book[i] == 1)
                cerr << i << " ";

        }
        cerr << "| ";
        for (int i = 1; i <= n; i++) {
            if (book[i] == 0)
                cerr << i << " ";

        }
        cerr << endl;
        cerr << "lowcost:" << endl;
        for (int i = 1; i <= n; i++) {
            if (j == i)

                cerr << i << "*" << "\t";
            else
                cerr << i << " " << "\t";
        }
        cerr << endl;
        for (int i = 1; i <= n; i++) {
            if (lowcost[i] == INF)
                cerr << "INF\t";
            else
                cerr << lowcost[i] << "\t";
        }
        cerr << endl;


        book[j] = 1;
        ++cnt;
        tot += lowcost[j];
        for (int k = 1; k <= n; k++) {//j加入到已经扩展的集合后，再利用j来更新lowcost，
            if (book[k] == 0 && dis[j][k] < lowcost[k]) {
                lowcost[k] = dis[j][k];
            }
        }
    }
    if (cnt < n)
        return -1;//图不连通
    else
        return tot;

}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    ifstream fin("graph.in");
    if (fin.good()) cin.rdbuf(fin.rdbuf());

    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++) {
            if (i == j)dis[i][j] = 0;
            else dis[i][j] = INF;
        }
    while (m--) {
        int x, y, w;
        cin >> x >> y >> w;
        dis[x][y] = dis[y][x] = w;
    }


    cout << Prim(1) << endl;

    return 0;
}
